/*
  dtostrf - Emulation for dtostrf function from avr-libc
  Copyright (c) 2013 Arduino.  All rights reserved.
  Written by Cristian Maglie <c.maglie@bug.st>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdio.h>
#include <string.h>

#define PRINT_BUF_LEN 12
static size_t printNumber(char *buffer, unsigned long cnt, uint8_t width) {
	char buf[PRINT_BUF_LEN]; // Assumes 8-bit chars plus zero byte.
	char *str = &buf[PRINT_BUF_LEN - 1];
	char en = 0;

	*str = '\0';
	do {
		char c = cnt % 10;
		cnt    = cnt / 10;
		*--str = c + '0';
		en++;
	} while (cnt);

	while (en < width) {
		*--str = ' ';
		en++;
	}

	strcpy(buffer, str);
	return en;
}

char *dtostrf (double number, signed char width, unsigned char digits, char *sout) {
	size_t n = 0;
	char *str = sout;
	// Handle negative numbers
	if (number < 0.0) {
		*str++ = '-';
		number = -number;
	}
	// Extract the integer part of the number and print it
	unsigned long int_part = (unsigned long) number;
	double remainder = number - (double) int_part;
	n = printNumber(str, int_part, width);
	str += n;
	if (remainder != 0) {
		// Print the decimal point, but only if there are digits beyond
		if (digits > 0) {
			*str++ = '.';
		}
		// Extract digits from the remainder one at a time
		while (digits-- > 0 && remainder != 0) {
			remainder *= 10.0;
			int toPrint = (int) (remainder);
			*str++ = toPrint + '0';
			remainder -= toPrint;
		}
		*str = 0;
	}
//	return str - buff;

//  char fmt[20];
//  sprintf(fmt, "%%%d.%df", width, prec);
//  sprintf(sout, fmt, val);
  return sout;
}

